package com.slt.concurrency.mashibing2019.juc.c_007_LockAndTools.exercise;

import java.util.Arrays;
import java.util.concurrent.CountDownLatch;

/**
 * 增强for循环不能用来 赋值
 */
public class CountDownLatch01 {
    public static void main(String[] args) {
        usingCountDownLatch();
        usingJoin();
    }

    private static void usingJoin() {
        Thread [] threads = new Thread[100];
//        for (Thread thread : threads) {
//            thread = new Thread(()->{
//                System.out.println(Thread.currentThread().getName());
//            });
//        }
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(()->{
                System.out.println(Thread.currentThread().getName());
            });
        }
        for (Thread thread : threads) {
            thread.start();
        }

        Arrays.stream(threads).forEach(t-> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("end join");
    }

    private static void usingCountDownLatch() {
        Thread [] threads = new Thread[100];
        CountDownLatch countDownLatch = new CountDownLatch(threads.length);
        //给数组赋值
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(()->{
                countDownLatch.countDown();
            });
        }
        //启动所有线程
        for (Thread thread : threads) {
            thread.start();
        }

        try {
            //只有一个线程await，检查  等待所有线程执行完毕
            countDownLatch.await();
            System.out.println("end latch");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
